const app = getApp()
const uploadOss = require('../../../utils/upload/uploadImg.js')
import { saveFile, saveOrUpdateMaterial, getDemandDetail } from '../../../api/index'
import { uuid } from '../../../utils/util'

Page({
  data: {
    addressPicker: false,
    categoryPicker: false,
    form: {
      id: '',
      demandName: '',
      demandParentCategory: '',
      demandChildCategory: '',
      location: '',
      projectScale: '',
      contactPerson: '',
      contactPhone: '',
      isPublic: false,
      demandDescription: '',
      fileIdList: [],
      fileList: []
    },
    inputDisabled: false,
    fileList: [],
    cateValue: '',
  },
  selectCate () {
    this.setData({ categoryPicker: true, inputDisabled: true })
  },
  closeCateModal () {
    this.setData({ categoryPicker: false, inputDisabled: false })
  },
  changeCate ({ detail: values }) {
    this.setData({
      cateValue: values[0].label + '-' + values[1].label,
      'form.demandParentCategory': values[0].value,
      'form.demandChildCategory': values[1].value,
      categoryPicker: false,
      inputDisabled: false
    })
  },
  selectAdress () {
    this.setData({ addressPicker: true, inputDisabled: true })
  },
  closeAddressModal () {
    this.setData({ addressPicker: false, inputDisabled: false })
  },
  changeAddress ({ detail: values }) {
    this.setData({
      'form.location': values[0].label + values[1].label,
      addressPicker: false,
      inputDisabled: false
    })
  },
  changeInput ({ currentTarget: { dataset: { key } }, detail }) {
    this.setData({
      ['form.'+ key]: detail.value
    })
  },
  changeCheckbox ({ currentTarget: { dataset: { key } } }) {
    this.data.form[key] = !this.data.form[key]
    this.setData({ ['form.' + key]: this.data.form[key] })
  },
  async submit () {
    try {
      let filters = ['demandName', 'demandParentCategory', 'demandChildCategory', 'location', 'projectScale', 'contactPerson', 'contactPhone', 'demandDescription']
      let valid = filters.every(key => this.data.form[key])
      let fileValid = !!this.data.form.fileList.length
      let reg = /^[1][2,3,4,5,6,7,8,9][0-9]{9}$/
      let mobileValid = reg.test(this.data.form.contactPhone)
      if (!valid || !fileValid || !mobileValid) {
        wx.showToast({ title: '请仔细核对内容是否有误！', icon: 'none' })
        return
      }
      let query = { ...this.data.form }
      query.fileIdList = this.data.form.fileList.map(item => { return item.fileId })
      await saveOrUpdateMaterial({ ...query })
      wx.showToast({ title: '发布成功！', icon: 'success' })
      wx.$nav.navigateBack()
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async chooseMedia () {
    try {
      let _this = this
      const { tempFiles } = await wx.$pro.chooseMedia({ mediaType: 'image' })
      tempFiles.forEach(item => {
        item.uuid = uuid()
        item.progress = 0
      })
      _this.data.fileList.push(...tempFiles)
      _this.setData({
        fileList: _this.data.fileList
      })
      let tempFileLists = _this.data.fileList
      let temFileList = []
      if (tempFileLists.length) {
        wx.showLoading({ title: '正在上传图片...' })
        temFileList = await Promise.all(tempFileLists.map(async (item, index) => {
          if (!item.fileId) {
            const { fileUrl } = await _this.uploadFile(item, 'tempFilePath', tempFileLists, index, _this, 'fileList')
            if (fileUrl) {
              const { ResultSet } = await saveFile({
                fileList: [{
                  fileSize: item.size,
                  fileUrl: fileUrl
                }]
              })
              return {
                uuid: item.uuid,
                fileId: ResultSet.userData.fileIdList[0].fileId,
                fileUrl: ResultSet.userData.fileIdList[0].fileUrl
              }
            } else {
              tempFileLists[index].success = 1
              _this.setData({
                fileList: tempFileLists
              })
            }
          } else {
            return {}
          }
        }))
        let temFilterFileList = temFileList.filter(item => item.fileId)
        this.data.form.fileList.push(...temFilterFileList)
        this.data.form.fileList.forEach(item => {
          if (item.uuid) {
            let rowIndex = tempFileLists.findIndex(row => row.uuid === item.uuid)
            if (rowIndex > -1) tempFileLists.splice(rowIndex, 1)
          }
        })
        _this.setData({
          fileList: tempFileLists,
          'form.fileList': this.data.form.fileList
        })
        wx.hideLoading()
      }
    } catch (err) {
      wx.hideLoading()
      console.log(err)
    }
  },
  uploadFile (item, key, files = '', index = '', that = '', dataKey = '') {
    return new Promise((resolve, reject) => {
      uploadOss(item[key],
        (res) => {
          resolve(res)
        },
        (err) => {
          wx.hideLoading()
          resolve()
        },
        files, index, that, dataKey
      )
    })
  },
  async getDetail () {
    try {
      const { ResultSet } = await getDemandDetail({ id: this.data.form.id })
      this.data.form = { ...this.data.form, ...ResultSet.userData.detail }
      this.data.cateValue = ResultSet.userData.detail.demandCategoryStr
      this.setData({
        form: this.data.form,
        cateValue: this.data.cateValue
      })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad ({ id }) {
    this.setData({ 'form.id': id })
    if (id) this.getDetail()
  }
})